package com.warrior.superdata.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.Enumeration;

/**
 * @Description:
 * @ClassName: RequestUtil.java
 * @date: 2022/8/30 15:30
 * @author xujian
 */
@Slf4j
public class RequestUtil {

    public static Object getBodyParam(HttpServletRequest request) {
        Object result = new JSONObject();
        StringBuffer sb = new StringBuffer();
        BufferedReader bufferReader = null;
        String line = null;
        try {
            bufferReader = new BufferedReader(request.getReader());
            while ((line = bufferReader.readLine()) != null) {
                sb.append(line);
            }
            try {
                result = JSONObject.parseObject(sb.toString());
            } catch (Exception e) {
                log.warn("请求参数为Lit");
                result = JSONArray.parseArray(sb.toString());
            }
        } catch (Exception e) {
            log.error("获取body参数异常 errMsg:{}", e.getMessage());
        } finally {
            if (null != bufferReader) {
                try {
                    bufferReader.close();
                } catch (Exception e) {
                    log.error("关流异常", e.getMessage());
                }
            }
        }
        return result;
    }

    public static Object getUrlParam(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Enumeration enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            jsonObject.put(paraName, request.getParameter(paraName));
        }
        return jsonObject;
    }

}
